package com.ymatou.query.seller.trading.api.parameter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.database.sqlwapper.YmtOrdersWapper;
import com.ymttest.database.sqlwapper.YmtRefundWapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.constant.DateConstant;

import freemarker.template.utility.DateUtil;

/**
 * 存储过程： sp_trd_GetOrderFundDetail_v1
 * 
 * @author songyefeng
 *
 */
@SuppressWarnings("rawtypes")
public class Sp_GetOrderFundDetail_v1 {
	private Integer orderId;
	private Boolean summary = false;

	public void setOrderId(Integer orderId) {
		this.orderId = orderId;
	}

	public void setSummary(Boolean summary) {
		this.summary = summary;
	}

	public void execute() {
		YmtOrdersWapper ordersWapper = new YmtOrdersWapper();
		DefaultWapper defaultWapper = new DefaultWapper();
		if (orderId == null || orderId == 0) {
			return;
		}
		Boolean shangou;// 定金+尾款、全额
		Integer status;// 订单状态 (取消状态为12,13,18)
		Integer refund;// 是否存在退款
		List<Map> t = ordersWapper.selectOrders2(
				"bShangouOrder, iTradingStatus, iSalesRefundStatus", null,
				"iOrderId = " + orderId);
		if (DataUtil.isNullOrEmpty(t)) {
			return;
		}
		Map order = t.get(0);
		shangou = DataUtil.Booleann.GetValueOrNull(order.get("bShangouOrder"));
		status = DataUtil.Integerr.GetValueOrNull(order.get("iTradingStatus"));
		refund = DataUtil.Integerr.GetValueOrNull(order
				.get("iSalesRefundStatus"));

		StringBuffer queryField = new StringBuffer();
		queryField.append("top 1 [time] = [order].dPaidTime ");
		queryField
				.append(", [cash] = [state].fPaidAmountOfCash , [gift] = fPaidAmountOfGift , [freeCard] = fPaidAmountOfFreeCard , [coupon] = [state].fPaidAmountOfYmtCoupon");
		queryField
				.append(", [couponChannel] = iif([order].fYmtCouponAmount > 0 and [order].fSellerCouponAmount > 0 , 3 , [order].iCouponChannel)");
		queryField.append(", [couponCode] = [order].sCouponCode");
		queryField
				.append(", [total] = isnull([state].fPaidAmountOfCash, 0) + isnull([state].fPaidAmountOfGift, 0) + isnull([state].fPaidAmountOfFreeCard, 0) + isnull([state].fPaidAmountOfYmtCoupon, 0)");
		queryField
				.append(", [occurredPrice] = [order].fOrderPrice , [priceChange] = [order].fOrderDiscount , [freight] = [order].fFreight");
		queryField
				.append(", [evidence] = null , [isIncoming] = convert(bit,1) , [operation] = 1 , [sellerCouponCode] = [order].sSellerCouponCode");
		queryField
				.append(", [sellerCoupon] = [state].fPaidAmountOfSellerCoupon");
		queryField
				.append(", [accountPaidAmount] = isnull([state].fPaidAmountOfCash, 0) - isnull(IIF(isnull([state].fPaidAmountOfThirdParty, 0) > 0, [state].fPaidAmountOfThirdParty, [tradingInfo].fAmount), 0)");
		queryField
				.append(", [thirdPartyPaidAmount] = iif(isnull([state].fPaidAmountOfThirdParty, 0) > 0, [state].fPaidAmountOfThirdParty, [tradingInfo].fAmount)");
		queryField.append(", [thirdPartyName] = [tradingInfo].[sPayChannel]");
		String joinCondition = "join [dbo].[Ymt_Orders] as [order] with(nolock) on [state].[iOrderId] = [order].[iOrderId] and [order].[dPaidTime] is not null";
		joinCondition += " outer apply (";
		joinCondition += " select top 1 [fAmount], [sPayChannel] ";
		joinCondition += " from [dbo].[Ymt_TradingInfo] with(nolock) ";
		joinCondition += " where [state].[fPaidAmountOfCash] > 0 and [iTradingId] = [order].iTradingId and [iTradingStatus] = 2 ";
		joinCondition += " ) as [tradingInfo]";
		/*
		 * 资金明细 : 付款方式：定金+尾款 or 全额if @status in (2,3,4,16,17) begin
		 * 只要付款时间不为NULL就表明发生了交易
		 */
		List<Map> t1 = defaultWapper.selectOrderStatesByOrderIds(
				queryField.toString(), joinCondition, "state.iOrderId = "
						+ orderId);
		if (DataUtil.isNullOrEmpty(t1) == false) {
			FlowsDetail o = new FlowsDetail();
			Map m = t1.get(0);
			DataUtil.mapToBean(o, m);
			FundDetails.add(o);
		}

		if (shangou == true && (status == 3 || status == 4 || status == 17)) {
			StringBuffer queryField2 = new StringBuffer();
			queryField2.append("top 1 [time] = [order].dPostPaidTime");
			queryField2
					.append(", [cash] = [state].fPostPaidAmountOfCash , [gift] = fPostPaidAmountOfGift , [freeCard] = 0 , [coupon] = convert(decimal,0)");
			queryField2.append(", [couponChannel] = 0 , [couponCode] = null ");
			queryField2
					.append(", [total] = [state].fPostPaidAmountOfCash + [state].fPostPaidAmountOfGift");
			queryField2
					.append(", [occurredPrice] = [state].fPostPaidAmountOfCash+[state].fPostPaidAmountOfGift");
			queryField2
					.append(", [priceChange] = [state].fPostPaidAmountOfCash+[state].fPostPaidAmountOfGift-([order].fTotalPrice-[order].fOrderPrice) ");
			queryField2
					.append(", [freight] = 0 , [evidence] = null , [isIncoming] = convert(bit,1) , [operation] = 2 , [sellerCouponCode] = null");
			queryField2.append(", [SellerCoupon] = 0");
			queryField2
					.append(", [accountPaidAmount] = isnull([state].fPostPaidAmountOfCash, 0) - isnull(IIF(isnull([state].fPostPaidAmountOfThirdParty, 0) > 0, [state].fPostPaidAmountOfThirdParty, [tradingInfo].Amount), 0)");
			queryField2
					.append(", [thirdPartyPaidAmount] = iif(isnull([state].fPostPaidAmountOfThirdParty, 0) > 0, [state].fPostPaidAmountOfThirdParty, [tradingInfo].Amount)");
			queryField2
					.append(", [thirdPartyName] = [tradingInfo].sPayChannel");
			String joinCondition2 = "join [dbo].[Ymt_Orders] as [order] with(nolock) on [state].[iOrderId] = [order].[iOrderId]";
			joinCondition2 += " outer apply (";
			joinCondition2 += " select top 1 b.[Amount] , a.[sPayChannel] ";
			joinCondition2 += " from [dbo].[Ymt_OrderPostPay] as a with(nolock)";
			joinCondition2 += " left join Ymt_PostPayTradingInfo as b with(nolock) on b.PostPayTradingId = a.sPostPayTradingId";
			joinCondition2 += " where [state].fPostPaidAmountOfCash > 0 and a.iOrderId = [order].iOrderId and a.iAction = 1 and b.OrderId = [order].iOrderId and b.[Action] = 1";
			joinCondition2 += " ) as [tradingInfo]";
			// 定金：需要追加尾款
			List<Map> t2 = defaultWapper
					.selectOrderStatesByOrderIds(
							queryField2.toString(),
							joinCondition2,
							"[state].iorderid = "
									+ orderId
									+ " and [order].bPaidInFull = 1 and [state].fPostPaidAmountOfCash > 0");
			if (DataUtil.isNullOrEmpty(t2) == false) {
				FlowsDetail o = new FlowsDetail();
				Map m = t2.get(0);
				DataUtil.mapToBean(o, m);
				FundDetails.add(o);
			}
		}

		if (status == 12 || status == 13 || status == 18) {
			StringBuffer sb = new StringBuffer();
			sb.append("[time] = [SettlementTime] ");
			sb.append(", [cash] = [CashAmount] , [gift] = convert(decimal,0) , [freeCard] = convert(decimal,0) , [couponAmount] ");
			sb.append(", [couponChannel] = 0 ,[couponCode] =null , [total] = [CashAmount] + isnull([CouponAmount],0) ,[occurredPrice] = 0 , [priceChange] = 0");
			sb.append(", [freight] = 0 , [evidence] = null, [isIncoming] = convert(bit,0),  [operation] = 4 , [sellerCouponCode] = null");
			sb.append(", [sellerCoupon] = 0 , [accountPaidAmount] = 0 , [thirdPartyPaidAmount] = 0 , [thirdPartyName] =null");
			List<Map> l = new DefaultWapper().selectSettlementInvoice(
					sb.toString(), null, "[BusinessType] = 3 and [OrderId] ="
							+ orderId);
			if (DataUtil.isNullOrEmpty(l) == false) {
				for (Map m : l) {
					FlowsDetail o = new FlowsDetail();
					DataUtil.mapToBean(o, m);
					FundDetails.add(o);
				}
			}
		}

		if (refund != null) {
			StringBuffer queryField3 = new StringBuffer();
			queryField3.append("[time] = AddTime");
			queryField3
					.append(", [cash] = RefundedAmountOfCash , [gift] = RefundedAmountOfGift, [freeCard] = 0 , [coupon] = SettlementAmountOfCoupon");
			queryField3
					.append(", [couponChannel] = iif(SettlementAmountOfCoupon > 0, 1, 0) , [couponCode] = null");
			queryField3
					.append(", [total]= RefundAmount + isnull(SettlementAmountOfCoupon, 0) , [occurredPrice] = RefundAmount , [priceChange] = 0");
			queryField3
					.append(", [freight] = 0 , [evidence] = RefundBillNo, [isIncoming] = convert(bit,0), [operation] = 3 , [sellerCouponCode] = null");
			queryField3
					.append(", [sellerCoupon] = 0 , [accountPaidAmount] = 0 , [thirdPartyPaidAmount] = 0 , [thirdPartyName] = null");
			// 退款
			List<Map> t3 = new YmtRefundWapper()
					.selectRefundBill2(
							queryField3.toString(),
							null,
							"[OrderId] = "
									+ orderId
									+ " and [SalesRefundStatus] = 10 and [RefundStatus] = 1");
			if (DataUtil.isNullOrEmpty(t3) == false) {
				for (Map m : t3) {
					FlowsDetail o = new FlowsDetail();
					DataUtil.mapToBean(o, m);
					FundDetails.add(o);
				}
			}
		}

		// 结果数据：订单的付款类型
		NeedPayTwiceOrMore = shangou;

		if (summary == null || summary == false) {
			return;
		}

		StringBuffer queryField4 = new StringBuffer();
		queryField4.append("state.fPaidAmountOfCash as paidCash");
		queryField4.append(",state.fPaidAmountOfGift as paidGift");
		queryField4.append(",state.fPaidAmountOfFreeCard as paidFreeCard");
		queryField4.append(",state.fPaidAmountOfYmtCoupon as paidYmtCoupon");
		queryField4
				.append(",state.fPaidAmountOfSellerCoupon as paidSellerCoupon");
		queryField4.append(",state.fPostPaidAmountOfCash as postPaidCash");
		queryField4.append(",state.fPostPaidAmountOfGift as postPaidGift");
		queryField4.append(",ISNULL(state.fDiscountOfThirdParty, 0) as totalThirdPartyDiscount");
		queryField4.append(",o.fTotalPrice as totalProductPrice");
		queryField4.append(",o.fOrderPrice as firstPayProductPrice");
		queryField4.append(",o.fFreight as freight");
		queryField4.append(",o.fOrderDiscount as orderDiscount");
		queryField4.append(",o.fDiscount as postPayDiscount");
		queryField4.append(",o.[fSellerPromotionAmount] as totalActivityPrice");
		queryField4.append(",[refund].totalRefundedCash");
		queryField4.append(",[refund].totalRefundedGift");
		queryField4.append(",[refund].totalRefundedYmtCoupon");
		queryField4.append(",[cancel].*");

		StringBuffer joinCondition4 = new StringBuffer();
		joinCondition4
				.append("join [dbo].[Ymt_Orders] as o with(nolock) on state.iorderid = o.iorderid");
		joinCondition4.append(" outer apply (");
		joinCondition4
				.append("	select sum(isnull(RefundedAmountOfCash,0)) as TotalRefundedCash");
		joinCondition4
				.append(" , sum(isnull(RefundedAmountOfGift,0)) as TotalRefundedGift");
		joinCondition4
				.append(" , sum(isnull(SettlementAmountOfCoupon,0)) as TotalRefundedYmtCoupon");
		joinCondition4.append(" from [dbo].[Ymt_RefundBill] with(nolock)");
		joinCondition4
				.append(" where OrderId = o.iOrderId and SalesRefundStatus = 10 and RefundStatus = 1");
		joinCondition4.append(" ) as [refund]");
		joinCondition4.append(" outer apply (");
		joinCondition4
				.append(" select sum(isnull([CashAmount],0)) as TotalCanceledCash");
		joinCondition4
				.append(", sum(isnull([CouponAmount],0)) as TotalCanceledYmtCoupon");
		joinCondition4
				.append("	from [dbo].[Ymt_SettlementInvoice]  with(nolock)");
		joinCondition4.append("	where [BusinessType] = 3 and [OrderId] = "
				+ orderId);
		joinCondition4.append(" ) as [cancel]");
		List<Map> t4 = defaultWapper.selectOrderStatesByOrderIds(
				queryField4.toString(), joinCondition4.toString(),
				"state.iorderid = " + orderId);
		if (DataUtil.isNullOrEmpty(t4) == false) {
			Summary = new FundSummary();
			Map m = t4.get(0);
			DataUtil.mapToBean(Summary, m);
		}
	}

	private List<FlowsDetail> FundDetails = new ArrayList<FlowsDetail>();
	private boolean NeedPayTwiceOrMore;
	private FundSummary Summary;

	public List<FlowsDetail> getFundDetails() {
		return FundDetails;
	}

	public boolean isNeedPayTwiceOrMore() {
		return NeedPayTwiceOrMore;
	}

	public FundSummary getSummary() {
		return Summary;
	}

	public static void main(String[] args) {
		Sp_GetOrderFundDetail_v1 sp = new Sp_GetOrderFundDetail_v1();
		sp.setOrderId(112449098);
		sp.execute();
	}

}
